#!/usr/bin/perl

# ---------- Init variables -------
#my $version = "0.0001";
# ---------- external readable parameters -------
## Functions
##-------------------------------------------------------
#
# stict syntax checking.
use strict;
use CGI qw(param);
use SIM_settings;
use SIM_base;
use strict;

#BEGIN { $Exporter::Verbose=1 }

# Startupscript translater
my $module = $ARGV[0];
my $tool = $ARGV[1];
my $action = $ARGV[2];
my $option1 = $ARGV[3];
my $option2 = $ARGV[4];
my $option3 = $ARGV[5];



my $backHeader="black";
my $httpUser = $ENV{'REMOTE_USER'};
my $httpReF = $ENV{'HTTP_REFERER'};
my $httpScriptName = $ENV{'SCRIPT_NAME'};
my $httpUserIp = $ENV{'REMOTE_ADDR'};
my $httpServerName = $ENV{'HTTP_HOST'};
my $httpCookie = $ENV{'HTTP_COOKIE'};
my $httpHost = $ENV{'HTTP_HOST'};
my $dloadDir = $ENV{'SIM_DLOADSTMPDIR'};
my $domainDir = $ENV{'SIM_DOMAINDIR'};
my $pluginDir = $ENV{'SIM_PLUGINSDIR'};
my $extraDir = $ENV{'SIM_EXTRAD'};
my $ipDataB = $ENV{'SIM_IPDATAB'};
my $globalDir = "$extraDir/vpn/globals";

sub catFile {
  my $output = "";
  my ($file) = @_;
  open FH, $file or $output = "none";
# $output = readline FH;
  $output = <FH>;
  close FH;
  return $output;
}

sub catFileLine {
  my $outPut = "";
  my ($file) = @_;
  open FH, $file or $outPut = "$file";
  $outPut = <FH>;
  close FH;
  chomp($outPut);  # remove the newline
  return $outPut;
}

sub printFileLine {
  my $file = "@_[0]";
  my $varName = "@_[1]";
  my $rest = "@_[2]";
  my $logFile = "@_[3]";
  my $oldVal = catFileLine ("$file");
# print ("Update file=$file, varName=$varName, content:$rest<BR>");
  if ( "$oldVal" ne "$rest" ) {
    open(OUT, ">$file") || die "cannot create $file: $! (file=$file, varName=$varName, rest=$rest)";
    if ( "$logFile" ne "quiet" ) {
      print ("$varName is gewijzigd, oud:$oldVal nieuw:$rest<BR>");
    }
    print OUT $rest;
    close(OUT);
  }
}

sub printDescription {
  my $ipAddr = "@_[0]";
  my $description = "@_[1]";
  my ( $ip1, $ip2, $ip3, $ip4 ) = split('\.', $ipAddr);
  my $workDir = "$ipDataB/$ip1/$ip2/$ip3/$ip4";
  if ( ! -d $workDir ) {
    system("mkdir -p $workDir");
  }
  printFileLine("$workDir/description","description","$description","quiet");
}

sub testParam {
  my $file = "@_[0]";
  my $parameter = "@_[1]";
  my $update = "@_[2]";
  my $result = param("$parameter");
  if ( "$result" eq "" ) {
#   print("cat ");
    $result = &catFileLine("$file");
  } else {
    if ( "$update" eq "upd" ) { 
      printFileLine("$file","$parameter","$result","nquiet");
    }
  }
# print("$result $file<BR>");
  return("$result");
}

sub testNameStrict {
  my $testname = "@_[0]";
  my $type = "@_[1]";
  if ( "$type" eq "word" ) {
    $testname =~ tr#a-zA-Z[\xE0][\xE8][\xEC][\xF2][\xF9]##cd;
  } else {
    $testname =~ tr#a-zA-Z0-9[\@][\.][\-]#A#cds;
  }
  #print ("testname=$testname");
  return $testname;
}

sub testMkDir {
  my $dirName = "@_[0]";
  if ( !-d $dirName ) {
    system "mkdir -p $dirName";
  }
}

sub expandIp {
  my $ipAddr = "@_[0]";
  my @pieces = split('\.', $ipAddr);
  my $returnIp;

  foreach my $chunk (@pieces) {
    my $eChunk = sprintf("%03d", $chunk);
    if ( "$returnIp" eq "" ) {
      $returnIp = "$eChunk";
    } else {
      $returnIp = "$returnIp.$eChunk";
    }
  }
  return $returnIp;
}

sub calcIp {
  my $ipAddr = "@_[0]";
  my $mask = "@_[1]";
  my @pieces = split('\.', $ipAddr);
  my @mPieces = split('\.', $mask);
  my $returnIp;
  foreach my $chunk (@pieces) {
    my $eChunk = $chunk + $mPieces[0];
    if ( "$returnIp" eq "" ) {
      $returnIp = "$eChunk";
    } else {
      $returnIp = "$returnIp.$eChunk";
    }
    shift @mPieces;
  }
  return $returnIp;
}

sub calcMask {
  my $ipAddr = "@_[0]";
  my $mask = "255.255.255.255";
  my @pieces = split('\.', $ipAddr);
  my @mPieces = split('\.', $mask);
  my $returnIp;
  foreach my $chunk (@pieces) {
#   my $eChunk = $chunk + $mPieces[0];
    my $eChunk = $mPieces[0] - $chunk;;
    if ( "$returnIp" eq "" ) {
      $returnIp = "$eChunk";
    } else {
      $returnIp = "$returnIp.$eChunk";
    }
    shift @mPieces;
  }
  return $returnIp;
}


sub printHead {
  my $dispHead = "@_[0]";
  print("
        <TABLE WIDTH=100% BORDER=0 CELLSPACING=0><TR BGCOLOR=#EEEEEE><TD COLSPAN=3><CENTER>
        Options:
        <A HREF=$httpScriptName?$module+$tool+globals>Globals</A> |
        <A HREF=$httpScriptName?$module+$tool+routers>Routers</A> |
        <A HREF=$httpScriptName?$module+$tool+clients>Clients</A> 
	");
  if ( "$action" eq "updVpnRange" ) {
    print("| <A HREF=$httpScriptName?$module+$tool+generate+$option1>Generate</A>");
    print("| <A HREF=$httpScriptName?$module+$tool+removeVpn+$option1>Remove</A>");
  }
  print("
	</TD></TR>
	</TABLE>
        ");
}

sub runRemoveVpn {
  my $subnet = "@_[0]";
  my $confirm = "@_[1]";
  my $subnetName = expandIp($subnet);
  my $clientDir = "$extraDir/vpn/clients/$subnetName";
  if ( $subnet eq "" ) {
    print("<CENTER><H2>Oops, $subnet selected.</H2>");
  } elsif ( ! -d $clientDir ) {
    print("<CENTER><H2>Oops, range $subnet not found.</H2>");
  } elsif ( $confirm ne "confirm" ) {
    print("<CENTER>Confirm removal of range $subnet: <A HREF=$httpScriptName?$module+$tool+removeVpn+$subnet+confirm>Remove</A>.");
  } else {
    print("<CENTER>Searching definitions for $subnet.");
    my $tunnelNum = catFileLine("$clientDir/tunnelNum");
    my $tunFile = "$extraDir/vpn/ipsecNums/$tunnelNum";
    if ( -f $tunFile ) {
      print(" tunnel $tunnelNum. ");
      unlink( $tunFile );
      system(" rm -fr $clientDir");
      if ( ! -d $clientDir ) {
        print("removed.");
      }
    } else {
      print("Oops, problems removing tunnel \"$tunnelNum\".");
    }
    print("<HR>");
    &updClients;
  }
}

sub runGenConfigs {
  my $subnetName = "@_[0]";
  $subnetName = expandIp($subnetName);
  my $routerDir = "$extraDir/vpn/routers";
  my $clientDir = "$extraDir/vpn/clients/$subnetName";
  my $shortName = catFileLine("$clientDir/shortName");
  my $description = catFileLine("$clientDir/description");
  my $vendorStatus = catFileLine("$clientDir/vendorStatus");
  my $ipAddr = catFileLine("$clientDir/ipaddr");
  my $tftpDir = catFileLine("$globalDir/tftpDir");
  my $aclMask = catFileLine("$globalDir/aclMask");
  my $internalNets = catFileLine("$globalDir/internalNets");
  print("<CENTER><B>Generating configs for vendor $shortName, $ipAddr.</B></CENTER><BR>");
  my @routerList = <$routerDir/*>;
  print("<UL>");
  foreach my $entry (@routerList) {
    my $routerName = catFileLine("$entry/routerName");
    print("<LI><A HREF=#$routerName>$tftpDir/$routerName-conf</A>");
  }
  if ( "$vendorStatus" eq "On" ) {
    print("<LI><A HREF=#vendor>$tftpDir/vendor-$shortName.txt</A>");
  }
  print("</UL><HR>");
  my $vendorFile = "$tftpDir/vendor-$shortName.txt";
  open(VENDOR, ">$vendorFile") || die "cannot create $vendorFile: $!";
  print VENDOR ("! Voorbeeld configuratie voor VPN koppeling DLNet.
! Dit betreft een VOORBEELD file, gebaseerd op een eenvoudige koppeling met een Cisco
! router met 2 ethernet interfaces, zonder een verdere configuratie.
! Ook bevat deze configuratie geen beveiligingsinstellingen als userid's, passwords etc.
! Pas daar waar nodig zaken als interfacenummers e.d. aan als deze al in gebruik zijn.
! GEBRUIK OP EIGEN RISICO.
! Basis configuratie commando's
! Configureren Ethernet interface (staat default vaak op dhcp)
! Interface ethernet1
!   ip address  193.172.54.93 255.255.255.248
!   no shut
! ip route 0.0.0.0 0.0.0.0 193.172.54.89
!
! Encryptie methoden
!
crypto isakmp policy 1
  encr aes 256
  hash md5
  authentication pre-share
  group 2
!
crypto ipsec transform-set aes-256 esp-aes 256 esp-sha-hmac
!
router rip
  version 2
  redistribute static
  network 10.0.0.0


                \n");
  my $num = 1;
  my @routerList = <$routerDir/*>;
  foreach my $entry (@routerList) {
    my $routerName = catFileLine("$entry/routerName");
    my $routerIp = catFileLine("$entry/routerIp");
    my $managementIp = catFileLine("$entry/managementIp");
    my $tunnelSource = catFileLine("$entry/tunnelSource");
    my $ipMask = catFileLine("$entry/ipMask");
    my $sharedKey = catFileLine("$clientDir/$routerName-sharedKey");
    my $remoteIp = catFileLine("$clientDir/$routerName-remoteIp");
    my $tunnelNum = catFileLine("$clientDir/tunnelNum");
    my $vendorStatus = catFileLine("$clientDir/vendorStatus");;
    print("<A NAME=$routerName>Processing info for router $routerName.</A><BR>");
    my $routerFile = "$tftpDir/$routerName-conf";
    open(ROUTER, ">$routerFile") || die "cannot create $routerFile: $!";
    print ROUTER ("! Aanpassingen configuratie t.b.v. Vendor $shortName op router $routerName.\n");
    print ROUTER ("!\n");
    if ( "$vendorStatus" eq "On" ) {
      print VENDOR ("! Diverse acl's t.b.v. filtering, routemaps, etc.\n!\n");
      print ROUTER ("! -------------- Access-lists ------------------\n");
    }
    print ROUTER ("no ip access-list extended MAP_tunnel$tunnelNum\n");
    if ( "$vendorStatus" eq "On" ) {
      print ROUTER ("ip access-list extended MAP_tunnel$tunnelNum\n");
      print ROUTER ("  remark Acl t.b.v. ipsec markeren gre verkeer.\n");
      print ROUTER ("  permit gre host $routerIp host $remoteIp\n");
      print ROUTER ("!\n");
    }
    print VENDOR ("no ip access-list extended MAP_Tunnel$num\n");
    if ( "$vendorStatus" eq "On" ) {
      print VENDOR ("ip access-list extended MAP_Tunnel$num\n");
      print VENDOR ("  remark Acl t.b.v. ipsec markeren gre verkeer.\n");
      print VENDOR ("  permit gre host $remoteIp host $routerIp \n");
      print VENDOR ("!\n");
    }
    print ROUTER ("no ip access-list extended Ip_from_tunnel$tunnelNum\n");
    my $intIp = calcIp($ipAddr,$ipMask);
    my $neighbIntIp = calcIp($intIp,"0.0.0.1");
    if ( "$vendorStatus" eq "On" ) {
      print ROUTER ("ip access-list extended Ip_from_tunnel$tunnelNum\n");
      print ROUTER ("  remark Antispoofing en acl verkeer vanaf $shortName.\n");
      print ROUTER ("  remark Verfijnde filtering vindt plaats op de Firewall.\n");
      print ROUTER ("  permit ip $ipAddr $aclMask $internalNets\n");
      print ROUTER ("  permit icmp $ipAddr $aclMask host $intIp\n");
      print ROUTER ("  remark Rip updates.\n");
      print ROUTER ("  permit udp host $neighbIntIp eq 0 host 224.0.0.9 eq 0\n");
      print ROUTER ("  permit udp host $neighbIntIp eq 520 host 224.0.0.9 eq 520\n");
      print ROUTER ("  deny ip any any log\n");
      print ROUTER ("!\n");
    }
    print ROUTER ("no ip access-list extended Ip_from_the_internet\n");
    print ROUTER ("ip access-list extended Ip_from_the_internet\n");
    print ROUTER ("  remark Strikt filteren alle verkeer vanaf het internet.\n");
    print ROUTER ("  remark toegestaan zijn: ping, en ipsec naar specifieke hosts.\n");
    my @clients = <$extraDir/vpn/clients/*>;
    foreach my $aclClient (@clients) {
      my $remoteAclIp = catFileLine("$aclClient/$routerName-remoteIp");
      my $clientAclDescr = catFileLine("$aclClient/description");
      my $clientStatus = catFileLine("$aclClient/vendorStatus");
      if ( "$clientStatus" eq "On" ) {
	print ROUTER ("  remark $clientAclDescr\n");
	#print ROUTER ("  permit icmp host $remoteAclIp host $routerIp echo\n");
	#print ROUTER ("  permit icmp host $remoteAclIp host $routerIp echo-reply\n");
	print ROUTER ("  permit icmp host $remoteAclIp host $routerIp\n");
	print ROUTER ("  permit udp host $remoteAclIp host $routerIp eq isakmp\n");
	print ROUTER ("  permit esp host $remoteAclIp host $routerIp\n");
      }
    }
    print ROUTER ("  deny ip any any log\n");
    print ROUTER ("!\n");
    if ( "$vendorStatus" eq "On" ) {
      print ROUTER ("no ip access-list standard Rip_to_Vendors \n");
      print ROUTER ("ip access-list standard Rip_to_Vendors \n");
      print ROUTER ("  remark Generieke acl voor uitgaande rip filtering.\n");
      print ROUTER ("  permit $internalNets\n");
      print ROUTER ("!\n");
    }
    print ROUTER ("no ip access-list standard Rip_from_tunnel$tunnelNum \n");
    if ( "$vendorStatus" eq "On" ) {
      print ROUTER ("ip access-list standard Rip_from_tunnel$tunnelNum \n");
      print ROUTER ("  remark Ingaande acl specifiek voor de vendor adresrange.\n");
      print ROUTER ("  permit $ipAddr $aclMask\n");
      print ROUTER ("!\n");
      print ROUTER ("!\n");
      print VENDOR ("! Tunneldefinities voor tunnel$num\n");
      print ROUTER ("! ---------------Tunneldefinities ----------------\n");
    }
    if ( "$vendorStatus" eq "On" ) {
      print ROUTER ("crypto isakmp key $sharedKey address $remoteIp\n");
      print VENDOR ("crypto isakmp key $sharedKey address $routerIp\n");
    } else {
      print ROUTER ("no crypto isakmp key $sharedKey address $remoteIp\n");
      print VENDOR ("no crypto isakmp key $sharedKey address $routerIp\n");
    }
    if ( "$vendorStatus" eq "On" ) {
      print ROUTER ("!\n");
      print VENDOR ("!\n");
      print ROUTER ("crypto map IPSEC-internet $tunnelNum ipsec-isakmp\n");
      print VENDOR ("crypto map IPSEC-internet $num ipsec-isakmp\n");
      print ROUTER ("  description $description\n");
      print VENDOR ("  description Tunnel$num naar DLNet.\n");
      print ROUTER ("  set peer $remoteIp\n");
      print VENDOR ("  set peer $routerIp\n");
      print ROUTER ("  set transform-set aes-256\n");
      print VENDOR ("  set transform-set aes-256\n");
      print ROUTER ("  match address MAP_tunnel$tunnelNum\n");
      print VENDOR ("  match address MAP_Tunnel$num\n");
      print ROUTER ("!\n");
      print VENDOR ("!\n");
    } else {
      print ROUTER ("no crypto map IPSEC-internet $tunnelNum ipsec-isakmp\n");
      print VENDOR ("no crypto map IPSEC-internet $num ipsec-isakmp\n");
    }
    if ( "$vendorStatus" eq "On" ) {
      print ROUTER ("interface Tunnel$tunnelNum\n");
      print VENDOR ("interface Tunnel$num\n");
      print ROUTER ("  description TUN $description\n");
      print VENDOR ("  description Tunnel$num naar DLNet.\n");
      print ROUTER ("  ip address $intIp 255.255.255.252\n");
      print VENDOR ("  ip address $neighbIntIp 255.255.255.252\n");
      printDescription("$neighbIntIp","Tunnel$tunnelNum on $routerName, $shortName");
      print ROUTER ("! ip mtu \n");
      print VENDOR ("! ip mtu \n");
      print ROUTER ("  keepalive 5 3\n");
      print VENDOR ("  keepalive 5 3\n");
      print ROUTER ("  tunnel source $tunnelSource\n");
      print VENDOR ("  ! De tunnelsource aanpassen aan de interface aan de internet zijde.\n");
      print VENDOR ("  tunnel source Ethernet1\n");
      print ROUTER ("  tunnel destination $remoteIp\n");
      print VENDOR ("  tunnel destination $routerIp\n");
      print ROUTER ("  ip access-group Ip_from_tunnel$tunnelNum in\n");
      print ROUTER ("!\n");
      print ROUTER ("interface $tunnelSource\n");
      print ROUTER ("  ip access-group Ip_from_the_internet in\n");
      print ROUTER ("!\n");
      print VENDOR ("!\n");
    } else {
      print ROUTER ("no interface Tunnel$tunnelNum\n");
      print VENDOR ("no interface Tunnel$num\n");
    }
    if ( "$vendorStatus" eq "On" ) {
      print VENDOR ("interface ethernet1\n");
      print VENDOR ("  crypto map IPSEC-internet\n");
      print VENDOR ("!\n");
    }
    print ROUTER ("! ------------------ Rip definities -------------------\n");
    print ROUTER ("router rip\n");
    if ( "$vendorStatus" eq "On" ) {
      print ROUTER (" distribute-list Rip_to_Vendors out Tunnel$tunnelNum\n");
      print ROUTER (" distribute-list Rip_from_tunnel$tunnelNum in Tunnel$tunnelNum\n");
      print ROUTER ("!\n");
      print ROUTER ("! ----- Ping responsetime metingen op tunnel $tunnelNum. -----\n");
    } else {
      print ROUTER (" no distribute-list Rip_to_Vendors out Tunnel$tunnelNum\n");
      print ROUTER (" no distribute-list Rip_from_tunnel$tunnelNum in Tunnel$tunnelNum\n");
      print ROUTER ("!\n");
      print ROUTER ("no ip sla monitor $tunnelNum\n");
    }
    #print ROUTER ("no rtr $tunnelNum\n");
    #print ROUTER ("rtr $tunnelNum\n");
    #print ROUTER ("  type echo protocol ipIcmpEcho $neighbIntIp\n");
    #print ROUTER ("  timeout 1000\n");
    #print ROUTER ("  frequency 300\n");
    #print ROUTER ("  lives-of-history-kept 2\n");
    #print ROUTER ("  buckets-of-history-kept 10\n");
    #print ROUTER ("  filter-for-history all\n");
    #print ROUTER ("rtr schedule $tunnelNum life forever start-time now\n");
    #print ROUTER ("rtr restart $tunnelNum\n");
    print ROUTER ("end\n");

    close ROUTER;
    print("<PRE>");
    if ( "$vendorStatus" eq "On" ) {
      print("! SLA monitor met de hand knippen en plakken i.v.m. bug in confnet.\n");
      print ("no ip sla monitor $tunnelNum\n");
      print ("ip sla monitor $tunnelNum\n");
      print ("  type echo protocol ipIcmpEcho $neighbIntIp source-ipaddr $intIp\n");
      print ("  frequency 300\n");
      print ("  request-data-size 64\n");
      print ("  tos 0\n");
      print ("  timeout 2000\n");
      print ("  tag $shortName\n");
      print ("ip sla monitor schedule $tunnelNum life forever start-time now\n");
      print ("!\n");
    } else {
      print ROUTER ("no ip sla monitor $tunnelNum\n");
    }
    system("cat $routerFile");
    print("</PRE><HR>");
    $num++;
  }
  print VENDOR ("end\n");
  close VENDOR;
  if ( "$vendorStatus" eq "On" ) {
    print("<A NAME=vendor>Basisconfig voor de Vendor.</A>
	   <PRE>");
    system("cat $vendorFile");
    print("</PRE>");
  }


  #open(OUT, ">$file") || die "cannot create $file: $! (file=$file, varName=$varName, rest=$rest)";
}

sub testIpAddr {
  my $ipAddr = "@_[0]";
  my @ipArr = split('\.', $ipAddr);
  my $result = "";
  foreach my $entry (@ipArr) {
    if (( $entry ge 0 ) and ( $entry < 256 )) {
      $result = "$result x";
    } else {
      $result = "$result y";
    }
  }
  if ( "$result" eq " x x x x" ) {
    return 1;
  }
}

sub testNameStrict {
  my $testname = "@_[0]";
  my $type = "@_[1]";
  if ( "$type" eq "word" ) {
    $testname =~ tr#a-zA-Z[\xE0][\xE8][\xEC][\xF2][\xF9]##cd;
  } else {
    $testname =~ tr#a-zA-Z0-9[\@][\.][\-]#A#cds;
  }
  return $testname;
}

sub expandIp {
  my $ipAddr = "@_[0]";
  my @pieces = split('\.', $ipAddr);
  my $returnIp;
  foreach my $chunk (@pieces) {
    my $eChunk = sprintf("%03d", $chunk);
    if ( "$returnIp" eq "" ) {
      $returnIp = "$eChunk";
    } else {
      $returnIp = "$returnIp.$eChunk";
    }
  }
  return $returnIp;
}

		    


sub updRouters {
  my $option1 = "@_[0]";
  my $workDir = "$extraDir/vpn/routers";
  if ( ! -d $workDir ) {
    system("mkdir -p $workDir");
  }
  if ( ! -d $workDir ) {
    print("Oops, no extraDir found. ($extraDir)");
    exit;
  }
  if (( -d "$workDir/$option1" ) and ( "$option1" ne "" )) {
    print("Removing info for router $option1.");
    system("rm -fR $workDir/$option1");
  }
  my $routerName = param("routerName");
  testNameStrict($routerName);
  my $tunnelSource = param("tunnelSource");
  my $routerIp = param("routerIp");
  my $ipMask = param("ipMask");
  my $managementIp = param("managementIp");
  if (( testIpAddr $routerIp ) and ( testIpAddr $managementIp ) and ( testIpAddr $ipMask ) and
      ( "$tunnelSource" ne "" ) and ( "$routerName" ne "" )) {
    my $routerDir = "$workDir/$routerName";
    testMkDir("$routerDir");
    printFileLine("$routerDir/routerName","routerName","$routerName");
    printFileLine("$routerDir/tunnelSource","tunnelSource","$tunnelSource");
    printFileLine("$routerDir/managementIp","managementIp","$managementIp");
    printFileLine("$routerDir/ipMask","ipMask","$ipMask");
    printFileLine("$routerDir/routerIp","routerIp","$routerIp");
    $routerName = "";
    $routerIp = "";
    $managementIp = "";
    $tunnelSource = "";
  }
  print("<CENTER><TABLE>
    <FORM method=post Action=$httpScriptName?$module+$tool+routers>
        <TR>
	  <TD>Router naam</TD><TD>Tunnel source interface</TD><TD>Ip mask</TD><TD>Management Ip</TD><TD>External Ip</TD>
	</TR><TR>
	  <TD>
	    <INPUT NAME=routerName SIZE=20 VALUE=\"$routerName\">
	  </TD><TD>
	    <INPUT NAME=tunnelSource SIZE=20 VALUE=\"$tunnelSource\">
	  </TD><TD>
	    <INPUT NAME=ipMask SIZE=15 VALUE=\"$ipMask\">
	  </TD><TD>
	    <INPUT NAME=managementIp SIZE=15 VALUE=\"$managementIp\">
	  </TD><TD>
	    <INPUT NAME=routerIp SIZE=15 VALUE=\"$routerIp\">
	  </TD>
	  <TD COLSPAN=2><INPUT TYPE=submit Value=\"Add router\"></TD>
	</TR>
        ");
  my @routers = <$workDir/*>;
  foreach my $entry (@routers) {
    my $routerName = catFileLine("$entry/routerName");
    my $tunnelSource = catFileLine("$entry/tunnelSource");
    my $managementIp = catFileLine("$entry/managementIp");
    my $routerIp = catFileLine("$entry/routerIp");
    my $ipMask = catFileLine("$entry/ipMask");
    print("<TR><TD>$routerName</TD><TD>$tunnelSource</TD><TD>$ipMask</TD><TD>$managementIp</TD><TD>$routerIp</TD>
      <TD><A HREF=$httpScriptName?$module+$tool+routers+$routerName>Delete router</A></TR>");
  }
  
  print("</TABLE>");
}

sub updClients {
  my $option1 = "@_[0]";
  my $option2 = "@_[1]";
  my $addVpnRange = param("addVpnRange");
  if ( "$addVpnRange" ne "" ) {
    if ( testIpAddr $addVpnRange ) {
      my $aclMask = catFileLine("$globalDir/aclMask");
      my $testMask = calcMask( $aclMask );
      my $testVpnRange = calcIpNet( $addVpnRange, $testMask );
      if ( $testVpnRange ne $addVpnRange ) {
        print("Updating range to $testVpnRange.<BR>");
        $addVpnRange = $testVpnRange;
      }
      &updVpnRange($addVpnRange);
      exit;
    }
  }
  print("<CENTER>
    <FORM method=post Action=$httpScriptName?$module+$tool+clients>
      <INPUT NAME=addVpnRange SIZE=20 VALUE=\"$addVpnRange\">
      <INPUT TYPE=submit Value=\"Add range\">
    </FORM>
        ");
  print("<TABLE>");
  chdir("$extraDir/vpn/clients");
  my @vendorList = <*>;
  foreach my $entry (@vendorList) {
    my $ipAddr = catFileLine("$entry/ipaddr");
    my $shortName = catFileLine("$entry/shortName");
    my $description = catFileLine("$entry/description");
    my $tunnelNum = catFileLine("$entry/tunnelNum");
    my $vendorStatus = catFileLine("$entry/vendorStatus");
    print("<TR><TD>Tunnel$tunnelNum</TD>
               <TD>$vendorStatus</TD>
               <TD><A HREF=$httpScriptName?$module+$tool+updVpnRange+$ipAddr>$ipAddr</A></TD>
               <TD>$shortName</TD><TD>$description</TD></TR>");
  }
  print("</TABLE>");
}

sub readUpdParam {
  my $workDir = "@_[0]";
  my $name = "@_[1]";
  my $param = param("$name");
  if ( "$param" eq "" ) {
    $param = catFileLine("$workDir");
  } else {
    printFileLine("$workDir","$name","$param");
  }
  return $param;
}

sub updVpnRange {
  my $option1 = "@_[0]";
  my $EIpAddr = expandIp($option1);
  my $workDir = "$extraDir/vpn/clients/$EIpAddr";
  if ( ! -d $workDir ) {
    testMkDir($workDir);
    printFileLine("$workDir/ipaddr","ipaddr","$option1");
    testMkDir("$extraDir/vpn/ipsecNums");
    foreach my $num (1 .. 1000) {
      if ( ! -f "$extraDir/vpn/ipsecNums/$num" ) {
        print("Assigned no $num<BR>");
        printFileLine("$extraDir/vpn/ipsecNums/$num","ipsecNum","$EIpAddr");
	printFileLine("$workDir/tunnelNum","tunnelNum","$num");
        last;
      } else {
        print(". $num .");
      }
    }
  }
  my $tunnelNum = catFileLine("$workDir/tunnelNum");
  my $shortName = readUpdParam("$workDir/shortName","shortName");
  my $description = readUpdParam("$workDir/description","description");
  my $vendorStatus = readUpdParam("$workDir/vendorStatus","vendorStatus");
  printFileLine("$workDir/shortName","shortName","$shortName");
  printFileLine("$workDir/description","description","$description");
  print("<CENTER><H2>Range $option1.</H2>
    <FORM method=post Action=$httpScriptName?$module+$tool+updVpnRange+$option1>
    <TABLE>
    <TR><TD>Tunnel:</TD><TD>$tunnelNum</TD></TR>
    <TR><TD>Status:</TD><TD><SELECT NAME=vendorStatus SIZE=1>
        <OPTION VALUE=$vendorStatus>$vendorStatus</OPTION>
        <OPTION VALUE=On>On</OPTION>
        <OPTION VALUE=Off>Off</OPTION>
      </SELECT>
    <TR><TD>Short name:</TD><TD><INPUT NAME=shortName SIZE=20 VALUE=\"$shortName\"></TD></TR>
    <TR><TD>Description:</TD><TD><INPUT NAME=description SIZE=80 VALUE=\"$description\"></TD></TR>
    </TABLE>
        ");
  my @routerInfo = <$extraDir/vpn/routers/*>;
  print("<TABLE>
         <TR BGCOLOR=#DDDDDD>
	   <TD>Router</TD>
	   <TD>Ip adres</TD>
	   <TD>Remote IP</TD>
	   <TD>Shared secret</TD>
	 </TR>
        ");
  foreach my $entry (@routerInfo) {
    my $routerName = catFileLine("$entry/routerName");
    my $routerIp = catFileLine("$entry/routerIp");
    my $remoteIp = readUpdParam("$workDir/$routerName-remoteIp","$routerName-remoteIp");
    my $sharedKey = readUpdParam("$workDir/$routerName-sharedKey","$routerName-sharedKey");
    print("<TR><TD>$routerName</TD><TD>$routerIp</TD>
               <TD><INPUT NAME=\"$routerName-remoteIp\" SIZE=20 VALUE=\"$remoteIp\"></TD>
	       <TD><INPUT NAME=\"$routerName-sharedKey\" SIZE=50 VALUE=\"$sharedKey\"></TD>
	   </TR>");
  }
  print("
         </FORM>
	 </TABLE>
	 <INPUT TYPE=submit Value=\"Update\">");
}

sub runGlobals {
  my $workDir = "$extraDir/vpn/globals";
  testMkDir($workDir);
  my $tftpDir = readUpdParam("$workDir/tftpDir","tftpDir");
  my $tftpDirFound = "Directory not found.";
  if ( -d $tftpDir ) {
    $tftpDirFound = "Directory present.";
  }
  my $aclMask = readUpdParam("$workDir/aclMask","aclMask");
  my $internalNets = readUpdParam("$workDir/internalNets","internalNets");
  print("<CENTER><TABLE>
    <FORM method=post Action=$httpScriptName?$module+$tool+globals>
    <TR><TD>Tftp directory</TD><TD><INPUT NAME=\"tftpDir\" SIZE=50 VALUE=\"$tftpDir\"></TD><TD>$tftpDirFound</TD></TR>
    <TR><TD>Internal range</TD><TD><INPUT NAME=\"internalNets\" SIZE=50 VALUE=\"$internalNets\"></TD></TR>
    <TR><TD>Adres mask ACL</TD><TD><INPUT NAME=\"aclMask\" SIZE=50 VALUE=\"$aclMask\"></TD></TR>
    </TABLE>
    <INPUT TYPE=submit Value=\"Update\">
       ");
}

#--------------------------- Main ---------------------------
printHead;

if ( "$action" eq "routers" ) {
  updRouters $option1;
} elsif ( "$action" eq "clients" ) {
  updClients($option1,$option2);
} elsif ( "$action" eq "updVpnRange" ) {
  updVpnRange($option1);
} elsif ( "$action" eq "removeVpn" ) {
  runRemoveVpn($option1,$option2);
} elsif ( "$action" eq "generate" ) {
  runGenConfigs($option1);
} elsif ( "$action" eq "globals" ) {
  runGlobals;
} else {
  print("Oops, action not coded ($tool).");
}
